const axios = require('axios');
const crypto = require('crypto');

// 移动接口配置
const config = {
  url: 'https://wap.wxcs.cn/mall/v1/deliverstatus/sync',
  privateKey: 'O0hiMEEdBT', // 移动分配的密钥
  apiId: 'deliverstatussync',              // 业务编码(由移动分配)
  channelCode: '10088',        // 渠道编码(由移动分配)
  mid: '10088',     // 供应商ID
  version: '1.0'               // 版本号
};

/**
 * 生成数字签名
 * @param {Object} params - 签名参数 
 * @returns {string} 32位大写MD5签名
 */
function generateSignature(params) {
  const { transactionId, reqTime, body } = params;
  
  // 1. 将body按键名自然排序
  const sortedBody = {};
  Object.keys(body)
    .sort()
    .forEach(key => {
      sortedBody[key] = body[key];
    });
  
  // 2. 将排序后的body转为紧凑JSON字符串
  const bodyString = JSON.stringify(sortedBody).replace(/\s+/g, '');
  //打印bodyString
  console.log('bodyString:', bodyString);
  // 3. 拼接签名字符串
  const signString = transactionId + reqTime + config.privateKey + bodyString;
  //打印signString
  console.log('signString:', signString);
  // 4. 生成MD5签名并转为大写
  return crypto.createHash('md5')
    .update(signString)
    .digest('hex')
    .toUpperCase();
}

/**
 * 格式化时间 (yyyyMMddHHmmssSSS)
 * @param {Date} date - 时间对象
 */
function formatTime(date) {
  const pad = n => n.toString().padStart(2, '0');
  return [
    date.getFullYear(),
    pad(date.getMonth() + 1),
    pad(date.getDate()),
    pad(date.getHours()),
    pad(date.getMinutes()),
    pad(date.getSeconds()),
    pad(date.getMilliseconds()).padStart(3, '0')
  ].join('');
}

/**
 * 推送支付状态到移动接口
 * @param {Object} orderData - 订单数据
 */
async function pushPaymentStatus(orderData) {
  // 生成请求流水号和时间戳
  const transactionId = `TX${Date.now()}${Math.floor(Math.random() * 10000)}`.slice(0, 30);
  const reqTime = formatTime(new Date());
  
  // 构建body内容
  // const requestBody = {
  //   msg_type: "paystatussyncreq",
  //   version: config.version,
  //   mid: config.mid,
  //   order_id: orderData.orderId,
  //   is_platform_order: orderData.isPlatformOrder ? 1 : 0,
  //   pay_organization: orderData.payOrg,
  //   pay_way: orderData.payWay,
  //   pay_type: orderData.payType,
  //   pay_time: formatPayTime(orderData.payTime),
  //   pay_status: 3, // 支付成功
  //   pay_price: Math.round(orderData.amount * 100)
  // };
  const requestBody = {
    is_compose: 1, // 新增字段
    is_platform_order: 0,
    mid: config.mid,
    msg_type: "deliverstatussyncreq",
    order_id: orderData.orderId,
    skus: [ // 修改为数组格式
      {
        deliver_time: formatTime(new Date()),
        id: orderData.spuId,
        status: 1,
        
      }
    ],
    spu_id: orderData.spuId, // 新增字段
    spu_name: orderData.spuName || "测试商品", // 新增字段
    status: 1, // 新增字段
    version: config.version,
  };

  //打印签名之前的字段
  console.log('transactionId:', transactionId);
  console.log('reqTime:', reqTime);
  console.log('body:', requestBody);
  console.log('body:', requestBody);
  console.log('body:', requestBody);
  console.log('body:', requestBody);
  console.log('body:', requestBody);
  // 生成数字签名
  const signature = generateSignature({
    transactionId,
    reqTime,
    body: requestBody
  });

  // 构建完整请求
  const fullRequest = {
    contractRoot: {
      head: {
        apiId: config.apiId,
        channelCode: config.channelCode,
        transactionId: transactionId,
        reqTime: reqTime,
        sign: signature,
        version: config.version
      },
      body: requestBody
    }
  };

  try {
    // 发送POST请求
    const response = await axios.post(config.url, fullRequest, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Connection': 'keep-alive'
      },
      timeout: 5000
    });

    // 处理响应
    const respData = response.data?.contractRoot || {};
    const respBody = respData.body || {};
    
    // 验证响应签名（可选）
    // 实际项目中可能需要验证响应签名
    //打印请求报文  
    console.log('请求报文:', JSON.stringify(fullRequest));
    console.log('响应报文:', JSON.stringify(respData));
    // 判断业务状态
    if (respBody.status == 0) {
      return { success: true, message: '推送成功' };
    }
    return {
      success: false,
      error: `移动返回错误: ${respBody.message || '未知错误'}`
    };
  } catch (error) {
    console.error('接口调用失败:', error.message);
    return {
      success: false,
      error: `请求异常: ${error.response?.data || error.message}`
    };
  }
}

/**
 * 格式化支付时间 (yyyyMMddHHmmss)
 * @param {Date} date - 支付时间对象
 */
function formatPayTime(date) {
  const pad = n => n.toString().padStart(2, '0');
  return [
    date.getFullYear(),
    pad(date.getMonth() + 1),
    pad(date.getDate()),
    pad(date.getHours()),
    pad(date.getMinutes()),
    pad(date.getSeconds())
  ].join('');
}



module.exports = pushPaymentStatus